<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" id="addAddressButton">
      <el-col :span="1.5" class="addButton">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:address:add']"
        >添加地址
        </el-button>
      </el-col>
      <!--            <el-col :span="1.5">-->
      <!--              <el-button-->
      <!--                type="success"-->
      <!--                plain-->
      <!--                icon="el-icon-edit"-->
      <!--                size="mini"-->
      <!--                :disabled="single"-->
      <!--                @click="handleUpdate"-->
      <!--                v-hasPermi="['system:address:edit']"-->
      <!--              >修改</el-button>-->
      <!--            </el-col>-->
      <!--            <el-col :span="1.5">-->
      <!--              <el-button-->
      <!--                type="danger"-->
      <!--                plain-->
      <!--                icon="el-icon-delete"-->
      <!--                size="mini"-->
      <!--                :disabled="multiple"-->
      <!--                @click="handleDelete"-->
      <!--                v-hasPermi="['system:address:remove']"-->
      <!--              >删除</el-button>-->
      <!--            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" class="table" :data="addressList" style="width: 80%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="收货人姓名" align="center" prop="name"/>
      <el-table-column label="电话" align="center" prop="phone"/>
      <el-table-column label="邮政编码" align="center" prop="postCode"/>
      <el-table-column label="省份/直辖市" align="center" prop="province"/>
      <el-table-column label="城市" align="center" prop="city"/>
      <el-table-column label="区" align="center" prop="region"/>
      <el-table-column label="详细地址(街道)" align="center" prop="detailAddress"/>
<!--      <el-table-column label="省市区代码" align="center" prop="areacode"/>-->
      <el-table-column label="是否默认" align="center" prop="defaultStatus" :formatter="isDefault"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:address:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:address:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改会员收货地址对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="form.name" placeholder="请输入收货人姓名"/>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话"/>
        </el-form-item>
        <el-form-item label="邮政编码" prop="postCode">
          <el-input v-model="form.postCode" placeholder="请输入邮政编码"/>
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-select v-model="form.province" placeholder="请输入省份" @change="refreshCity">
            <el-option v-for="item in this.areaList" v-if="item.type==1"
                       :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="form.city" placeholder="请输入城市" @change="refreshRegion">
            <el-option v-for="item in this.cityList"
                       :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区" prop="region">
          <el-select v-model="form.region" placeholder="请输入区">
            <el-option v-for="item in this.regionList"
                       :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="form.detailAddress" placeholder="请输入详细地址"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click="setDefault">设为默认</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import areas from "@/utils/areas";

export default {
  name: "Address",
  data() {
    return {
      cityList: [],
      regionList: [],
      areaList: areas,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员收货地址表格数据
      addressList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        memberId: null,
        name: null,
        phone: null,
        postCode: null,
        province: null,
        city: null,
        region: null,
        detailAddress: null,
        areacode: null,
        defaultStatus: null
      },
      defaultAddress: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{required: true, message: "用户名不能为空！", trigger: "blur"},],
        phone: [{required: true, message: "手机号不能为空！", trigger: "blur"},
          {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur'},
          {min: 11, max: 11, message: "请输入11位的手机号！", trigger: 'blur'}],
        postCode: [{required: true, message: "邮编不能为空！", trigger: "blur"},],
        province: [{required: true, message: "省份不能为空！", trigger: "blur"},],
        city: [{required: true, message: "城市不能为空！", trigger: "blur"},],
        region: [{required: true, message: "区域不能为空！", trigger: "blur"},],
        detailAddress: [{required: true, message: "详细地址不能为空！", trigger: "blur"},],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    refreshRegion() {
      this.form.region=undefined
      this.regionList=[];
      for (let i =0;i<areas.length;i++){
        if (areas[i].parentId==this.form.city){
          this.regionList.push(areas[i])
        }
      }
      return this.regionList
    },
    refreshCity() {
      this.form.city=undefined
      this.form.region=undefined
      this.cityList = [];
      this.regionList = [];
      for (let i = 0; i < areas.length; i++) {
        if (areas[i].parentId==this.form.province){
          this.cityList.push(areas[i])
        }
      }
      return this.cityList
    },
    isDefault(row, column, cellValue, index) {
      if (cellValue == 1) {
        return '默认地址'
      } else {
        return '普通地址'
      }
    },
    setDefault() {
      axios({
        url: 'member/address/setDefault',
        method: 'get',
        params: {
          id: this.form.id
        }
      }).then(response => {
        this.$message.success("修改成功");
        this.open = false;
        this.getList();
      })
    },
    /** 查询会员收货地址列表 */
    getList() {
      this.loading = true;
      // listAddress(this.queryParams).then(response => {
      //   this.addressList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
      axios({
        url: '/member/address/list',
        method: 'get',
        params: {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
        }
      }).then(response => {
        this.addressList = response.rows;
        this.total = response.total;
        if (this.form.defaultStatus == 1) {
          this.defaultAddress = '默认地址'
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        memberId: null,
        name: null,
        phone: null,
        postCode: null,
        province: null,
        city: null,
        region: null,
        detailAddress: null,
        areacode: null,
        defaultStatus: null
      };
      // this.resetForm("form");
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会员收货地址";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      // getAddress(id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改会员收货地址";
      // });
      axios({
        url: '/member/address/getAddress',
        method: 'get',
        params: {
          id: id
        }
      }).then(response => {
        console.log(response)
        this.form = response.data;
        this.open = true;
        this.title = "修改会员收货地址";
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (isNaN(this.form.region)){
              axios({
                url: '/member/address/updateAddress',
                method: 'post',
                data: {
                  id: this.form.id,
                  memberId: this.form.memberId,
                  name: this.form.name,
                  phone: this.form.phone,
                  postCode: this.form.postCode,
                  province: this.form.province,
                  city: this.form.city,
                  region: this.form.region,
                  detailAddress: this.form.detailAddress,
                  areacode: this.form.areacode,
                  defaultStatus: this.form.defaultStatus
                }
              }).then(response => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              })
            }else {
              axios({
                url: '/member/address/updateAddress',
                method: 'post',
                data: {
                  id: this.form.id,
                  memberId: this.form.memberId,
                  name: this.form.name,
                  phone: this.form.phone,
                  postCode: this.form.postCode,
                  province: areas[this.form.province-1].name,
                  city: areas[this.form.city-1].name,
                  region: areas[this.form.region-1].name,
                  detailAddress: this.form.detailAddress,
                  areacode: this.form.province+'_'+this.form.city+'_'+this.form.region,
                  defaultStatus: this.form.defaultStatus
                }
              }).then(response => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              })
            }

          } else {
            axios({
              url: '/member/address/addAddress',
              method: 'post',
              data: {
                pageNum: this.form.pageNum,
                pageSize: this.form.pageSize,
                memberId: this.form.memberId,
                name: this.form.name,
                phone: this.form.phone,
                postCode: this.form.postCode,
                province: areas[this.form.province-1].name,
                city: areas[this.form.city-1].name,
                region: areas[this.form.region-1].name,
                detailAddress: this.form.detailAddress,
                areacode: this.form.province+'_'+this.form.city+'_'+this.form.region,
                defaultStatus: this.form.defaultStatus
              }
            }).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {

      const ids = row.id || this.ids;
      console.log(ids)
      this.$confirm('是否确认删除该收货地址？').then(() => {
        axios({
          url: '/member/address/delAddress',
          method: 'get',
          params: {
            ids: ids
          }
        }).then()
      }).then(() => {
        this.getList();
        this.$message.success('删除成功');
      }).catch(() => {
      });
    },

  }
};
</script>
<style scoped>
.table {
  position: relative;
  top: -1170px;
  left: 140px;
}
.addButton{
  position: relative;
  top: -1250px;
  left: 100px;
}

#addAddressButton {
  position: relative;
  left: 60px;
  top: 50px;
}
</style>
